import { messages, queryCurrencyPrecision } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { message, Tag, Popover } from 'antd'
import moment from 'moment'
import config from 'config'
import FileSaver from 'file-saver'
import menuRoute from 'routes/menuRoute'
import constants from 'share/constants'
import errorMessage from 'share/errorMessage';
import SearchArea from 'components/search-area'
import ExportModal from 'components/template/export-modal/export-modal';
import costApplicationService from 'containers/financial-management/check-cost-application/check-cost-application.service'
import requestService from 'containers/request/request.service'
import 'styles/financial-management/finance-view.scss'
import CostCenterSearchForm from 'components/template/cost-center-search-form/cost-center-search-form'
import ResizeTable from 'components/resize-table'

class CheckCostApplication extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      exportLoading: false,
      status: [
        { label: messages('financial-management.key120'/*审批中*/), value: '1002', state: 'processing' },
        { label: messages('financial-management.key121'/*已通过*/), value: '1003', state: 'success' },
        { label: messages('financial-management.key122'/*已驳回*/), value: '1001', state: 'error' }
      ],
      searchForm: [
        {
          type: 'searcher',
          id: 'formOIDs',
          label: messages('financial-management.key176'/*表单类型*/),
          listType: 'authority_form',
          descriptionKey: 'companyName',
          labelKey: 'formName',
          valueKey: 'formOID',
          listExtraParams: { formType: 1001 }

        },
        {
          type: 'combobox', id: 'userOID', label: messages('financial-management.key123'/*申请人姓名/工号*/),
          placeholder: messages('common.please.enter') + messages('financial-management.key123'/*申请人姓名/工号*/),
          options: [], searchUrl: `${config.baseUrl}/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
          method: 'get', searchKey: 'keyword', labelKey: 'fullName', valueKey: 'userOID',
          renderOption: option => (`${option.eid}-${option.employeeID}-${option.fullName}${(option.status !== 1001 ? (
              `（${option.status === 1002 ? messages('financial-management.key622')/*待离职员工*/ :
                messages('financial-management.key623')/*离职员工*/}）`
            ) : '')}`)
        }, //申请人姓名/工号
        { type: 'input', id: 'businessCode', label: messages('financial-management.key125'/*单据ID*/) },
        {
          type: 'items', id: 'dateRange', items: [
          {
            type: 'date',
            id: 'beginDate',
            label: messages('financial-management.key126'/*提交日期从*/),
            defaultValue: moment().subtract(1, 'month')
          }, //提交日期从
          {
            type: 'date',
            id: 'endDate',
            label: messages('financial-management.key127'/*提交日期至*/),
            defaultValue: moment()
          } //提交日期至
        ]
        },
        {
          type: 'items', id: 'approvalDateRange', items: [
          { type: 'date', id: 'approvalStartDate', label: messages('financial-management.key193'/*审批日期从*/) },
          { type: 'date', id: 'approvalEndDate', label: messages('financial-management.key194'/*审批日期至*/) }
        ]
        },
        {
          type: 'list', id: 'departmentOIDs', label: messages('financial-management.key195'/*部门*/),
          listType: 'department', labelKey: 'name', valueKey: 'departmentOid'
        },
        {
          type: 'multiple',
          id: 'legalEntity',
          label: messages('financial-management.key128'/*法人实体*/),
          options: [],
          getUrl: `${config.baseUrl}/api/finance/role/legalEntity/query?page=0&size=100`,
          method: 'get',
          labelKey: 'entityName',
          valueKey: 'companyReceiptedOID',
          listKey: "rows"
        },
        {
          type: 'checkbox', id: 'status', label: messages('common.column.status'), colSpan: 24,
          options: [ //状态
            { label: messages('financial-management.key120'/*审批中*/), value: 'submitted' }, //审批中
            { label: messages('financial-management.key121'/*已通过*/), value: 'approval_pass' },  //已通过
            { label: messages('financial-management.key122'/*已驳回*/), value: 'approval_reject' }, //已驳回
            {
              label: messages("components.keyS03" /*待发货*/),
              value: "1014",
              state: "success",
            },
            {
              label: messages("components.keyS04" /*已发货*/),
              value: "1016",
              state: "success",
            },
            {
              label: messages("components.keyS05" /*已确认*/),
              value: "1017",
              state: "success",
            },
            {
              label: messages("components.keyS06" /*发货中*/),
              value: "1018",
              state: "success",
            },
            {
              label: messages("components.keyS07" /*待发放*/),
              value: "1019",
              state: "success",
            },
          ]
        },
      ],
      checkboxListForm: [
        {
          id: 'formOIDs',
          items: [
            { label: messages('financial-management.key129'/*费用申请单*/), key: 'cost', options: [] }
          ]
        }
      ],
      searchParams: {
        entityType: 1001,
      },
      columns: [
        {
          title: messages('common.sequence'),
          dataIndex: 'index',
          width: '7%',
          render: (text, record, index) => (this.state.page * this.state.pageSize + index + 1)
        },  //序号
        { title: messages('financial-management.key130'/*工号*/), dataIndex: 'employeeID' },
        {
          title: messages('financial-management.key131'/*申请人*/),
          dataIndex: 'applicant',
          render: value => <Popover content={value}>{value}</Popover>
        },
        {
          title: messages('financial-management.key132'/*提交日期*/),
          dataIndex: 'lastSubmittedDate',
          render: (date, record) =>
            date ? moment(date).format('YYYY-MM-DD') : moment(record.createDate).format('YYYY-MM-DD'),
          sorter: true
        },
        {
          title: messages('financial-management.key133'/*单据类型*/),
          dataIndex: 'formName',
          render: value => <Popover content={value}>{value}</Popover>
        },
        {
          title: messages('financial-management.key134'/*单号*/),
          dataIndex: 'businessCode',
          sorter: true,
          render: (value, record) => (
            <Popover content={record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}>
              {record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}
            </Popover>
          )
        },
        {
          title: messages('financial-management.key894')/*事由*/,
          dataIndex: 'title',
          render: value => {return <Popover placement="topLeft" content={value || '-'}>{value || '-'}</Popover>}
        },
        { title: messages('financial-management.key135'/*币种*/), dataIndex: 'currencyCode', width: 48 },
        {
          title: messages('financial-management.key136'/*总金额*/),
          dataIndex: 'totalAmount',
          render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)),
          sorter: true
        },
        {
          title: messages('common.column.status'),
          dataIndex: 'status',
          width: props.language.code === 'zh_cn' ? '8%' : '13%',
          render: (value, record) => {
            let applicationType = '';
            (+record.entityType === 1001) && (applicationType = 2005);//申请单下的applicationType是2005
            let text;
            let color;
            text = constants.getTextByValue(String(value + '' + applicationType), 'documentStatus') ||
              constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus') ||
              constants.getTextByValue(String(value), 'documentStatus');
            color = constants.getTextByValue(String(value + '' + applicationType), 'documentStatus', 'color') ||
              constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus', 'color') ||
              constants.getTextByValue(String(value), 'documentStatus', 'color')
            return <Tag color={color}>{text}</Tag>
          }
        },
        //状态
        {
          title: messages('common.operation'),
          dataIndex: 'operation',
          width: props.language.code === 'zh_cn' ? '7%' : '10%',
          render: (value, record) =>
            <a onClick={event => this.print(record, event)}>{messages('financial-management.key137'/*打印*/)}</a>
        }
      ],
      data: [],
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100', '200']
      },
      sort: '',
      pageSize: 10,
      page: 0,
      haveLoan: true,    //搜索单据包含借款单
      haveExpense: true, //搜索单据包含报销单
      costDetailView: menuRoute.getRouteItem('cost-application-detail', 'key'),//申请单详情
    }
  }

  componentWillMount() {
    let params = [
      { factorCode: "COMPANY", factorValue: this.props.user.companyId },
      { factorCode: "SET_OF_BOOKS", factorValue: this.props.company.setOfBooksId }
    ];
    requestService.searchPrintFree(this.props.user.tenantId, params).then(res => {
      if (res.data.rows[0].hitValue === 'Y') {
        let search = this.state.searchForm;
        search.push({
          type: 'select',
          id: 'printFree',
          label: messages('financial-management.key138'/*报销单是否免打印*/),
          options: [
            { label: messages('financial-management.key139'/*全部*/), value: null },
            { label: messages('financial-management.key140'/*免打印*/), value: true },
            { label: messages('financial-management.key141'/*非免打印*/), value: false }]
        });
        let length = search.length;
        let temp = search[length - 1];
        search[length - 1] = search[length - 2];
        search[length - 2] = temp;
        this.setState({ searchForm: search });
      }
    })
  }

  componentDidMount() {
    // this.getForms();
    this.getList(true)
  }

  //获取表单
  getForms = () => {
    let checkboxListForm = this.state.checkboxListForm;
    let params = {
      formType: 1001,
    };
    //获取费用申请单
    costApplicationService.getCostTypeList(params).then(res => {
      let options = [];
      res.data.map(list => {
        options.push({ label: list.formName, value: list.formOID })
      });
      checkboxListForm[0].items.map(item => {
        item.key === 'cost' && (item.options = options)
      })
      this.setState({ checkboxListForm })
    });
  };
  getList = (firstRequest) => {
    const { page, pageSize, searchParams, sort, pagination } = this.state;
    if (firstRequest) {
      searchParams.beginDate = moment().subtract(1, 'month').format('YYYY-MM-DD 00:00:00');
      searchParams.endDate = moment().format('YYYY-MM-DD 23:59:59');
    }
    this.setState({ loading: true });
    let isAudit = '1';
    costApplicationService.getFinanceViewList(page, pageSize, sort, searchParams, isAudit).then(res => {
      if (res.status === 200) {
        pagination.total = Number(res.headers['x-total-count']);
        pagination.current = page + 1;
        this.setState({
          loading: false,
          data: res.data,
          pagination
        });
      }
    }).catch((err) => {
      this.setState({ loading: false });
      errorMessage(err.response);
    })
  };

  search = (result) => {
    const { pagination } = this.state;
    let { searchParams }=this.state;
    result.beginDate && (result.beginDate = moment(result.beginDate).format('YYYY-MM-DD 00:00:00'));
    result.endDate && (result.endDate = moment(result.endDate).format('YYYY-MM-DD 23:59:59'));
    result.approvalStartDate && (result.approvalStartDate = moment(result.approvalStartDate).format('YYYY-MM-DD 00:00:00'));
    result.approvalEndDate && (result.approvalEndDate = moment(result.approvalEndDate).format('YYYY-MM-DD 23:59:59'));
    result.printFree === 'null' && (delete result.printFree);
    result.searchCorporations = result.legalEntity ? result.legalEntity : [];
    result.searchCostCenterCommands = searchParams.searchCostCenterCommands;
    pagination.total = 0;
    pagination.current = 1;
    this.setState({
      searchParams: result,
      page: 0,
      pagination
    }, this.getList);
  };

  clear = () => {
    this.handleSearchData();
    this.setState({ searchParams: {} })
  };

  handleSearchData = () => {
    let { searchForm } =this.state;
    let dateRange = searchForm.filter(item => item.id === 'dateRange')[0];
    dateRange.items[0].defaultValue = null;
    dateRange.items[1].defaultValue = null;
    this.setState({ searchForm })
  }

  //顶部横条checkbox搜索框处理事件
  handleCheckbox = (id, checked) => {
    let searchForm = this.state.searchForm;
    let haveLoan = true;
    let haveExpense = true;
    checked.map(list => {
      if (list.key === 'cost') {
        haveLoan = list.checked ? !!list.checked.length : false
      }
    });
    if (haveLoan !== this.state.haveLoan || haveExpense !== this.state.haveExpense) {
      this.formRef.setValues({
        status: ''
      })
    }
    searchForm.map(item => {
      item.id === 'status' && item.options.map(option => {
        if (option.value === 'paid_in_process' || option.value === 'paid_finish') {
          option.disabled = (!haveLoan && haveExpense)
        }
      })
    });
    this.setState({ haveLoan, haveExpense })
  };

  //导出事件
  handleExport = () => {
    const { searchParams } = this.state;
    this.setState({ exportLoading: true });
    costApplicationService.exportFinanceList(searchParams).then(res => {
      if (res.status === 200) {
        let b = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
        FileSaver.saveAs(b, messages('financial-management.key142'/*单据导出.xlsx*/));
        this.setState({ exportLoading: false });
        message.success(messages('financial-management.key143'/*导出成功*/))
      }
    }).catch(e => {
      this.setState({ exportLoading: false });
      let blob = new Blob([e.response.data]);
      let reader = new FileReader();
      reader.readAsText(blob);
      reader.addEventListener("loadend", () => {
        let result = reader.result;
        if (result && typeof result === 'string') {
          result = JSON.parse(result);
          if (result.message) {
            message.error(`${messages('financial-management.key144'/*导出失败*/)}，${result.message}`)
          } else {
            message.error(`${messages('financial-management.key144'/*导出失败*/)}，${result.message}`)
          }
        }
      });
      reader.addEventListener('error', () => {
        message.error(messages('financial-management.key144'/*导出失败*/))
      })
    })
  };

  handleRowClick = (record) => {
    // entityType：1001（申请单

    let url = `${this.state.costDetailView.url.replace(':formOID', record.formOID).replace(':applicationOID', record.entityOID)}?readOnly=true`;
    window.open((window.ISIE9 ? '#' : '') + url, '_blank');
  };

  //打印
  print = (record, event) => {
    event.preventDefault();
    event.stopPropagation();
    event.cancelBubble = true;
    costApplicationService.printApplicationReport(record.entityOID).then(res => {
      window.open(res.data.fileURL, '_blank');
    })
  };

  handleTableChange = (pagination, filters, sorter) => {
    let page = pagination.current;
    let sort = '';
    if (sorter.order) {
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`
    }
    this.setState({
      page: page - 1,
      pageSize: pagination.pageSize,
      sort
    }, this.getList);
  };

  renderExpandedRow = (title, content) => {
    return (
      <div>
        <span>{title}</span>
        {content && <span>:{content}</span>}
      </div>
    )
  };

  renderAllExpandedRow = (record) => {
    let result = [];
    if (record.printFree) {
      result.push(this.renderExpandedRow(messages('common.print.free'), messages('common.print.require')));
    }
    if (result.length > 0) {
      return result;
    } else {
      return null;
    }
  };

  changeCostCenter = (value) => {
    let searchParams = this.state.searchParams;
    searchParams.searchCostCenterCommands = value;
    this.setState({ searchParams })
  };
  render() {
    const { loading, exportLoading, searchForm, checkboxListForm, columns, data, pagination, searchParams } = this.state;
    return (
      <div className="finance-view">
        <SearchArea searchForm={searchForm}
                    extraFields={[
                      <div>
                        <div style={{ lineHeight: '28px' }}>
                          {/*成本中心*/}
                          {messages('financial-management.key145'/*成本中心*/)}
                        </div>
                        <CostCenterSearchForm title={messages('financial-management.key145'/*成本中心*/)}
                                              value={searchParams.searchCostCenterCommands}
                                              onChange={this.changeCostCenter}/>
                      </div>
                    ]}
                    extraFieldsIndex={7}
                    maxLength={6}
                    submitHandle={this.search}
                    clearHandle={this.clear}
                    checkboxChange={this.handleCheckbox}
                    wrappedComponentRef={(inst) => this.formRef = inst}
        />
        <div className="table-header">
          {/* <div className="table-header-buttons">
            <ExportModal
              type={"btn"}
              btnType="primary"
              exportTitle={messages('financial-management.key146')}
              exportType="FINANCE_APPLICAITON_CHECK"
              exportCondition={{
                billCheckSearchCommand: this.state.searchParams
              }}
              exportCommand={'FINANCE_APPLICAITON_CHECK'}/>
          </div> */}
          <div className="table-header-title">{messages('common.total', { total: pagination.total || 0 })}</div>
          {/*共多少条数据*/}
        </div>
        <ResizeTable
          rowKey={record => record.entityOID}
          columns={columns}
          dataSource={data}
          loading={loading}
          pagination={pagination}
          onChange={this.handleTableChange}
          onRow={record => ({ onClick: () => {this.handleRowClick(record)} })}
          expandedRowRender={this.renderAllExpandedRow}
          rowClassName={record => record.printFree ? '' : 'finance-view-reject'}
          bordered
          size="middle"
        />
      </div>
    )
  }
}

CheckCostApplication.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language
  }
}

export default connect(mapStateToProps)(CheckCostApplication);
